/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
/// <summary>
/// Summary description for ETextHelper
/// </summary>
namespace GearBlog.Web.Helpers
{
	using System;
	using System.Collections.Specialized;
	using System.IO;
	using System.Text.RegularExpressions;
	using Castle.MonoRail.Framework;
	using Castle.MonoRail.Framework.Helpers;
	using GearBlog.Web.ConfigSections;
	using Textile;
	
	public class ETextHelper:AbstractHelper
    {
		public static string Textilize(string source, IRailsEngineContext context)
		{
			StringBuilderTextileFormatter stringOutputter = new StringBuilderTextileFormatter();
			TextileFormatter formatter = new TextileFormatter(stringOutputter);
			//pre process source with additional rules
			source = PreProcess(source, context);
			formatter.Format(source);
			return stringOutputter.GetFormattedText();
		}
        public string Textilize(string source)
        {
        	return Textilize(source, CurrentContext);
            

        }
		private static string PreProcess(string source, IRailsEngineContext context)
		{
			MatchCollection matches = Regex.Matches(source, @"\[(?<key>\w+)\]",RegexOptions.IgnoreCase);
			StringDictionary keys=new StringDictionary();
			foreach (Match match in matches)
			{
				string key = match.Groups["key"].Value;
				if (!keys.ContainsKey(key)) keys.Add(key, key);
			}

			string result=source;
			foreach (string key in keys.Keys)
			{
				result = Regex.Replace(result, string.Format(@"(\[{0}\])", key), GetStoragePath(context, key));
			}
			return result;


		}
		private static string GetStoragePath(IRailsEngineContext context, string storageKey)
		{
			Storage storage = FileUploadComponentSection.GetSection().Storages[storageKey];
			string path = AppendIfNotExist(context.ApplicationPath,"/");
			return AppendIfNotExist(path + storage.Path, "/");
			
		}
		private static string AppendIfNotExist(string value, string endString)
		{
			if (!value.EndsWith(endString))
				value +=endString;
			return value;
		}

		
    }

}
